import 'package:flutter/material.dart';

/// @date 2020/08/05  10:44
/// @author 程志强
/// @des  异步UI更新  FutureBuilder

class FutureBuilderRoute extends StatefulWidget {
  @override
  _FutureBuilderRouteState createState() => _FutureBuilderRouteState();
}

class _FutureBuilderRouteState extends State<FutureBuilderRoute> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("异步UI更新：FutureBuilder"),
      ),
      body: Center(
        child: FutureBuilder(
            future: mockNetworkData(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              // 请求结束
              if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasError) {
                  // 请求失败，显示错误
                  return Text("Error：${snapshot.error}");
                } else {
                  // 请求成功，显示数据
                  return Text("Contents：${snapshot.data}");
                }
              } else {
                // 请求未结束，显示loading
                return CircularProgressIndicator();
              }
            }),
      ),
    );
  }

  // 模拟网络请求数据
  Future<String> mockNetworkData() {
    return Future.delayed(Duration(seconds: 2), () => "网络请求数据结果");
  }
}
